#!/bin/bash

# 账号密码管理系统 - 项目清理脚本
# 用于清理开发过程中的临时文件和文档,准备发布正式版

set -e  # 遇到错误立即退出

echo "========================================"
echo "  账号密码管理系统 - 项目清理脚本"
echo "========================================"
echo ""

# 切换到项目根目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"

echo "📂 项目根目录: $PROJECT_ROOT"
echo ""

# 询问用户确认
read -p "⚠️  此操作将清理开发文档和临时文件,是否继续? (y/N): " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ 已取消清理操作"
    exit 1
fi

echo ""
echo "🧹 开始清理..."
echo ""

# 1. 创建文档目录结构
echo "📁 创建文档目录结构..."
mkdir -p docs/archive
mkdir -p docs/api
mkdir -p docs/deployment
mkdir -p docs/development
mkdir -p docs/database
mkdir -p docs/user-guide
mkdir -p scripts/deployment
echo "   ✅ 文档目录创建完成"
echo ""

# 2. 归档开发文档
echo "📦 归档开发文档到 docs/archive/..."
ARCHIVE_FILES=(
    "ADDITIONAL_FEATURES.md"
    "AGENTS.md"
    "BUILD_FIX_SUMMARY.md"
    "CLEANUP_REPORT.md"
    "FEATURES_COMPLETED.md"
    "FINAL_SUMMARY.md"
    "FINAL_SUMMARY_V2.md"
    "I18N_PWA_SUMMARY.md"
    "IMPLEMENTATION_SUMMARY.md"
    "OPTIMIZATION_SUMMARY.md"
    "PROJECT_OPTIMIZATION_REPORT.md"
    "PROJECT_SUMMARY.md"
    "TODO.md"
)

for file in "${ARCHIVE_FILES[@]}"; do
    if [ -f "$file" ]; then
        mv "$file" docs/archive/
        echo "   ✅ 已归档: $file"
    else
        echo "   ⚠️  文件不存在: $file"
    fi
done
echo ""

# 3. 移动保留的文档
echo "📝 移动保留的文档..."
PRESERVE_DOCS=(
    "CHANGELOG.md:docs/"
    "DEPLOYMENT.md:docs/deployment/"
    "PERFORMANCE.md:docs/development/"
    "TESTING_GUIDE.md:docs/development/"
    "FEATURES.md:docs/development/"
)

for item in "${PRESERVE_DOCS[@]}"; do
    file="${item%%:*}"
    dest="${item##*:}"
    if [ -f "$file" ]; then
        mv "$file" "$dest"
        echo "   ✅ 已移动: $file -> $dest"
    else
        echo "   ⚠️  文件不存在: $file"
    fi
done

# README.md 保留副本
if [ -f "README.md" ]; then
    cp README.md docs/
    echo "   ✅ 已复制: README.md -> docs/"
fi
echo ""

# 4. 删除临时文件
echo "🗑️  删除临时文件..."
TEMP_FILES=(
    "claude-automation-headless.py"
    "claude_output_*.log"
    "tasks.txt"
)

for pattern in "${TEMP_FILES[@]}"; do
    if compgen -G "$pattern" > /dev/null; then
        rm -f $pattern
        echo "   ✅ 已删除: $pattern"
    else
        echo "   ⚠️  文件不存在: $pattern"
    fi
done
echo ""

# 5. 删除开发工具目录
echo "🗑️  删除开发工具目录..."
if [ -d "dev-tools" ]; then
    rm -rf dev-tools
    echo "   ✅ 已删除: dev-tools/"
else
    echo "   ⚠️  目录不存在: dev-tools/"
fi
echo ""

# 6. 移动部署脚本
echo "📦 移动部署相关脚本..."
DEPLOY_SCRIPTS=(
    "deploy.sh"
    "deploy.bat"
    "docker-compose.yml"
)

for file in "${DEPLOY_SCRIPTS[@]}"; do
    if [ -f "$file" ]; then
        mv "$file" scripts/deployment/
        echo "   ✅ 已移动: $file -> scripts/deployment/"
    else
        echo "   ⚠️  文件不存在: $file"
    fi
done

# start脚本移到scripts目录
START_SCRIPTS=(
    "start.sh"
    "start.bat"
)

for file in "${START_SCRIPTS[@]}"; do
    if [ -f "$file" ]; then
        mv "$file" scripts/
        echo "   ✅ 已移动: $file -> scripts/"
    else
        echo "   ⚠️  文件不存在: $file"
    fi
done
echo ""

# 7. 创建配置文件示例
echo "⚙️  创建配置文件示例..."

# 后端配置示例
if [ ! -f "backend/.env.example" ]; then
    cat > backend/.env.example << 'EOF'
APP_DEBUG = false
APP_TRACE = false

[DATABASE]
HOSTNAME = 127.0.0.1
DATABASE = accountmanage
USERNAME = root
PASSWORD = your_database_password
HOSTPORT = 3306
CHARSET = utf8mb4
PREFIX = am_

[REDIS]
HOST = 127.0.0.1
PORT = 6379
PASSWORD =
SELECT = 0

[JWT]
SECRET = your_jwt_secret_key_here_change_in_production
EXPIRE = 7200

[ENCRYPT]
KEY = your_encryption_key_here_32_characters_minimum
METHOD = AES-256-CBC

[APP]
NAME = 账号密码管理系统
VERSION = 1.0.0
URL = https://yourdomain.com

[LOG]
LEVEL = error
TYPE = file
PATH = runtime/log/
EOF
    echo "   ✅ 已创建: backend/.env.example"
else
    echo "   ⚠️  已存在: backend/.env.example"
fi

# 前端配置示例
if [ ! -f "frontend/.env.example" ]; then
    cat > frontend/.env.example << 'EOF'
# 应用标题
VITE_APP_TITLE=账号密码管理器

# API 基础地址
VITE_API_BASE_URL=http://localhost:8080

# API 超时时间（毫秒）
VITE_API_TIMEOUT=10000

# 是否启用Mock数据
VITE_USE_MOCK=false

# 是否启用PWA
VITE_PWA_ENABLED=true
EOF
    echo "   ✅ 已创建: frontend/.env.example"
else
    echo "   ⚠️  已存在: frontend/.env.example"
fi
echo ""

# 8. 更新.gitignore
echo "📝 更新 .gitignore..."
if ! grep -q "docs/archive/" .gitignore; then
    cat >> .gitignore << 'EOF'

# 开发文档归档
docs/archive/

# 编辑器备份文件
*.swp
*.swo

# 清理脚本生成的临时文件
cleanup.log
EOF
    echo "   ✅ 已更新: .gitignore"
else
    echo "   ⚠️  .gitignore 已包含相关规则"
fi
echo ""

# 9. 生成清理报告
echo "📄 生成清理报告..."
cat > CLEANUP_LOG.txt << EOF
账号密码管理系统 - 清理日志
====================================

清理时间: $(date '+%Y-%m-%d %H:%M:%S')

清理内容:
---------

1. 已归档的开发文档:
$(printf '   - %s\n' "${ARCHIVE_FILES[@]}")

2. 已移动的保留文档:
   - CHANGELOG.md -> docs/
   - DEPLOYMENT.md -> docs/deployment/
   - PERFORMANCE.md -> docs/development/
   - TESTING_GUIDE.md -> docs/development/
   - README.md (复制) -> docs/

3. 已删除的临时文件:
   - claude-automation-headless.py
   - claude_output_*.log
   - tasks.txt
   - dev-tools/ (目录)

4. 已移动的脚本:
   - deploy.sh -> scripts/deployment/
   - deploy.bat -> scripts/deployment/
   - docker-compose.yml -> scripts/deployment/
   - start.sh -> scripts/
   - start.bat -> scripts/

5. 已创建的配置文件:
   - backend/.env.example
   - frontend/.env.example

6. 项目结构:
   docs/
   ├── archive/           # 开发文档归档
   ├── api/               # API文档
   ├── deployment/        # 部署文档
   ├── development/       # 开发文档
   ├── database/          # 数据库文档
   └── user-guide/        # 用户手册

   scripts/
   ├── deployment/        # 部署脚本
   ├── start.sh          # 启动脚本
   └── start.bat         # Windows启动脚本

下一步:
-------
1. 查看 RELEASE_CHECKLIST.md 了解发布前的完整检查清单
2. 修复严重的安全问题（特别是AES加密）
3. 创建生产环境配置文件（复制.env.example并填写实际值）
4. 完善文档（API文档、部署文档等）
5. 进行全面测试

EOF

echo "   ✅ 清理报告已保存到: CLEANUP_LOG.txt"
echo ""

echo "========================================"
echo "✅ 清理完成！"
echo "========================================"
echo ""
echo "📋 清理摘要:"
echo "   - 已归档 ${#ARCHIVE_FILES[@]} 个开发文档到 docs/archive/"
echo "   - 已移动 5 个保留文档到 docs/"
echo "   - 已删除临时文件和开发工具"
echo "   - 已创建配置文件示例"
echo "   - 已更新 .gitignore"
echo ""
echo "📝 下一步建议:"
echo "   1. 查看 RELEASE_CHECKLIST.md 了解发布清单"
echo "   2. 查看 CLEANUP_LOG.txt 了解详细清理记录"
echo "   3. 复制配置文件: cp backend/.env.example backend/.env"
echo "   4. 修改配置文件中的敏感信息（密钥、密码等）"
echo "   5. 修复严重安全问题（参考 RELEASE_CHECKLIST.md）"
echo ""
echo "💡 提示: 所有开发文档已归档到 docs/archive/,可随时查看"
echo ""
